package com.uton.rfidcontroller.common.net;

import com.google.gson.FieldNamingPolicy;
import com.google.gson.GsonBuilder;
import com.uton.rfidcontroller.R;
import com.uton.rfidcontroller.common.utils.LogUtil;
import com.uton.rfidcontroller.common.utils.SharedPreferencesUtils;
import com.uton.rfidcontroller.common.utils.Utils;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by 王家宝 on 2017/8/30.
 * Email:639586819@qq.com
 * Tel:18241150668
 */
public class RetrofitFactory {
    /*本地测试*/
//    private static final String BASE_URL = "http://192.168.1.173:8090/";
    /*正式服*/
    private static final String BASE_URL = "http://rfid.utonw.com/";
    /*灰度测试*/
//    private static final String BASE_URL = "http://rfidg.utonw.com/";
    private static final long TIMEOUT = 10;
    private static final String RESPONSE_TOKEN = "token";
    private static final String REQUEST_TOKEN = "token";
    private static final String CONTENT_TYPE = "Content-Type";
    private static final String CONTENT_TYPE_VALUE = "application/json;charset=UTF-8";
    private static final String DEVICE_TYPE = "deviceType";
    private static final String TYPE_ANDROID = "3";
    private static final String APP_ID = "appId";
    private static final String APP_ID_CONTENT = "RFID-1000";
    private static final String API_VERSION = "api-version";
    private static final String VERSION = "1.0";
    private static final String USER_ID = "userId";
    private static final String DEPRECATED = "xxxxx1";


    private static OkHttpClient httpClient = new OkHttpClient.Builder()
            .addInterceptor(new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {
                    Request.Builder builder = chain.request().newBuilder();
                    builder.addHeader(CONTENT_TYPE, CONTENT_TYPE_VALUE).
                            addHeader(SharedPreferencesUtils.getToken().length() != 0 ? REQUEST_TOKEN : DEPRECATED,
                                    SharedPreferencesUtils.getToken()).
                            addHeader(DEVICE_TYPE, TYPE_ANDROID).
                            addHeader(APP_ID, APP_ID_CONTENT).
                            addHeader(USER_ID, SharedPreferencesUtils.getUserID()).
                            addHeader(API_VERSION, VERSION);

                    Response originalResponse = chain.proceed(builder.build());
                    if (!originalResponse.headers(RESPONSE_TOKEN).isEmpty()) {
                        for (String token : originalResponse.headers(RESPONSE_TOKEN)) {
                            SharedPreferencesUtils.saveToken(token);
                        }
                    } else {
                        LogUtil.d(Utils.getString(R.string.log_get_token_error));
                    }

                    return originalResponse;
                }
            })
            .addInterceptor(new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
                @Override
                public void log(String message) {
                    LogUtil.d(message != null ? message : Utils.getString(R.string.log_no_message));
                }
            }).setLevel(HttpLoggingInterceptor.Level.BODY))
            .connectTimeout(TIMEOUT, TimeUnit.SECONDS)
            .readTimeout(TIMEOUT, TimeUnit.SECONDS)
            .build();

    private static RetrofitService retrofitService = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create(
                    new GsonBuilder()
                            .serializeNulls()
                            .setFieldNamingPolicy(FieldNamingPolicy.IDENTITY)
//                            .registerTypeAdapter(BaseModel.class, new UserTypeAdapter())
                            .setPrettyPrinting()
                            .create()
                    )
            )
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .client(httpClient)
            .build()
            .create(RetrofitService.class);

    public static RetrofitService getInstance() {
        return retrofitService;
    }

}
